angular.module("app", ["ui.router", "ngSanitize", "ngResource", "ui.bootstrap", "dx"]);
angular.module("app").config(["$stateProvider", "$urlRouterProvider", "$locationProvider", "$httpProvider", function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
    $httpProvider.defaults.withCredentials = true;
    $httpProvider.defaults.transformResponse = function (data, headersGetter, status) {
        if (status !== 200) {
            alert("服务器开了小差, 请刷新或联系管理员");
            sessionStorage.clear();
            location.href = "#/login";
            return;
        }
        if (headersGetter()["content-type"] == "application/json;charset=UTF-8") {
            data = angular.fromJson(data);
            if (location.hash == "#/login") return data;
            if (data.statusCode == -100) {
                alert("系统服务连接异常!");
                location.href = "#/login";
            } else if (data.statusCode == -1) {
                alert("用户未登录");
                location.href = "#/login";
            }
        }
        return data;
    };
    $urlRouterProvider.when("", "/login");
    $urlRouterProvider.otherwise("/home/404");
    $stateProvider
        .state("login", {
            url: "/login",
            views: {
                "mainContent": {
                    templateUrl: "template/login/login.html?tk=" + new Date().getTime(),
                    controller: "loginCtrl"
                }
            }
        })
        .state("home", {
            url: "/home",
            views: {
                "mainContent": {
                    templateUrl: "template/home/home.html?tk=" + new Date().getTime(),
                    controller: "homeCtrl"
                }
            },
            resolve: {
                // "treeViewDataSource": ["User", function (User) {
                //     return User.getTreeData({}, {test: 1}, function (data) {
                //     }).$promise;
                // }],
                "qiniuToken": ["User", function (User) {
                    return User.getConfig({}, {orgId: JSON.parse(sessionStorage.userInfo).orgId}, function (data) {
                    }).$promise;
                }]
            }
        })
        .state("resetPassword", {
            url: "/resetPassword",
            views: {
                "mainContent": {
                    templateUrl: "template/resetPassword/resetPassword.html?tk=" + new Date().getTime(),
                    controller: "resetPassword.Ctrl"
                }
            }
        })
        .state("home.welcome", {
            url: "/welcome",
            views: {
                "viewContent": {
                    templateUrl: "template/home/welcome/welcome.html?tk=" + new Date().getTime(),
                    controller: "welcomeCtrl"
                }
            }
        })
        // .state("home.setting", {
        //     url: "/setting",
        //     views: {
        //         "viewContent": {
        //             templateUrl: "template/home/setting/setting.html?tk=" + new Date().getTime(),
        //             controller: "settingCtrl"
        //         }
        //     }
        // })
        // .state("home.org", {
        //     url: "/org",
        //     abstract: true,
        //     views: {
        //         "viewContent": {
        //             template: "<div ui-view='subview'><div/>"
        //         }
        //     }
        // })
        // .state("home.org.list", {
        //     url: "/list",
        //     views: {
        //         "subview": {
        //             templateUrl: "template/home/org/list/list.html?tk=" + new Date().getTime(),
        //             controller: "org.list.Ctrl"
        //         }
        //     }
        // })
        // .state("home.org.info", {
        //     url: "/info",
        //     views: {
        //         "subview": {
        //             templateUrl: "template/home/org/info/info.html?tk=" + new Date().getTime(),
        //             controller: "org.info.Ctrl"
        //         }
        //     }
        // })
        // .state("home.org.managerList", {
        //     url: "/managerList",
        //     views: {
        //         "subview": {
        //             templateUrl: "template/home/org/managerList/managerList.html?tk=" + new Date().getTime(),
        //             controller: "org.managerList.Ctrl"
        //         }
        //     }
        // })
        .state("home.welfare", {
            url: "/welfare",
            abstract: true,
            views: {
                "viewContent": {
                    template: "<div ui-view='subview'><div/>"
                }
            }
        })
        .state("home.welfare.list", {
            url: "/list",
            views: {
                "subview": {
                    templateUrl: "template/home/welfare/list/list.html?tk=" + new Date().getTime(),
                    controller: "welfare.list.Ctrl"
                }
            }
        })
        .state("home.welfare.info", {
            url: "/info/:type/:id",
            params: { welfareInfo: null },
            views: {
                "subview": {
                    templateUrl: "template/home/welfare/info/info.html?tk=" + new Date().getTime(),
                    controller: "welfare.info.Ctrl"
                }
            }
        })
        .state("home.welfare.welfareItemList", {
            url: "/welfareItemList",
            views: {
                "subview": {
                    templateUrl: "template/home/welfare/welfareItemList/welfareItemList.html?tk=" + new Date().getTime(),
                    controller: "welfare.welfareItemList.Ctrl"
                }
            }
        })
        // .state("home.group.verify", {
        //     url: "/verify",
        //     views: {
        //         "subview": {
        //             templateUrl: "template/home/group/verify/verify.html?tk=" + new Date().getTime(),
        //             controller: "group.verify.Ctrl"
        //         }
        //     }
        // })
        // .state("home.group.volunteerList", {
        //     url: "/volunteerList/:groupId",
        //     views: {
        //         "subview": {
        //             templateUrl: "template/home/group/volunteerList/volunteerList.html?tk=" + new Date().getTime(),
        //             controller: "group.volunteerList.Ctrl"
        //         }
        //     }
        // })
        // .state("home.group.activityList", {
        //     url: "/activityList/:userId",
        //     views: {
        //         "subview": {
        //             templateUrl: "template/home/group/activityList/activityList.html?tk=" + new Date().getTime(),
        //             controller: "group.activityList.Ctrl"
        //         }
        //     }
        // })
        .state("home.user", {
            url: "/user",
            abstract: true,
            views: {
                "viewContent": {
                    template: "<div ui-view='subview'><div/>"
                }
            }
        })
        .state("home.user.changePassword", {
            url: "/changePassword",
            views: {
                "subview": {
                    templateUrl: "template/home/user/changePassword/changePassword.html?tk=" + new Date().getTime(),
                    controller: "user.changePassword.Ctrl"
                }
            }
        })
        .state("home.user.manageList", {
            url: "/manageList",
            views: {
                "subview": {
                    templateUrl: "template/home/user/manageList/manageList.html?tk=" + new Date().getTime(),
                    controller: "user.manageList.Ctrl"
                }
            }
        })
        .state("home.user.manageInfo", {
            url: "/manageInfo/:type/:manageId",
            params: { manageInfo: null },
            views: {
                "subview": {
                    templateUrl: "template/home/user/manageInfo/manageInfo.html?tk=" + new Date().getTime(),
                    controller: "user.manageInfo.Ctrl"
                }
            }
        })
        .state("home.topic", {
            url: "/topic",
            abstract: true,
            views: {
                "viewContent": {
                    template: "<div ui-view='subview'><div/>"
                }
            }
        })
        .state("home.topic.list", {
            url: "/list",
            views: {
                "subview": {
                    templateUrl: "template/home/topic/list/list.html?tk=" + new Date().getTime(),
                    controller: "topic.list.Ctrl"
                }
            }
        })
        .state("home.topic.info", {
            url: "/info/:id",
            views: {
                "subview": {
                    templateUrl: "template/home/topic/info/info.html?tk=" + new Date().getTime(),
                    controller: "topic.info.Ctrl"
                }
            }
        })
        .state("home.topic.comments", {
            url: "/comments/:id",
            views: {
                "subview": {
                    templateUrl: "template/home/topic/comments/comments.html?tk=" + new Date().getTime(),
                    controller: "topic.comments.Ctrl"
                }
            }
        })
        ;
    $httpProvider.interceptors.push("timestampMarker");
}]);
angular.module("app").run(["$rootScope", function ($rootScope) {
    if (location.host.indexOf("localhost") >= 0) {
        // $rootScope.sysOrigin = "http://test.dakaqi.cn:3030/platform";
        $rootScope.sysOrigin = "/api";
    }
    else {
        $rootScope.sysOrigin = "/platform";
    }
    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
        if (toState.name.indexOf("home") >= 0 && !sessionStorage.userInfo) {
            event.preventDefault();
            location.href = "#/login";
        }
    })
}]);
/**
 * Created by cjd on 2016/5/4.
 */
angular.module("app").factory("timestampMarker", ["$rootScope", "$timeout", function ($rootScope, $timeout) {
    return {
        request: function (config) {
            var headersGetter = config.headers;
            if ((headersGetter["Accept"] && headersGetter["Accept"].split(",")[0]) == "application/json" && config["url"].indexOf("template") < 0) {
                $rootScope.loading = true;
                config.requestTimestamp = new Date().getTime();
                config.url = $rootScope.sysOrigin + config.url;
            }
            return config;
        },
        response: function (response) {
            response.config.responseTimestamp = new Date().getTime();
            return response;
        }
    };
}]);
angular.module("app")
    .factory("User", ["$resource", function ($resource) {
        return $resource("", {}, {
            Login: {
                cache: false,
                method: "POST",
                url: "/user/login",
                isArray: false
            },
            changePassword: {
                cache: false,
                method: "POST",
                url: "/user/changePassword",
                isArray: false
            },
            resetPassword: {
                cache: false,
                method: "POST",
                url: "/user/resetPassword",
                isArray: false
            },
            sendSMS: {
                cache: false,
                method: "POST",
                url: "/user/sendCode",
                isArray: false
            },
            // checkPassword: {
            //     cache: false,
            //     method: "POST",
            //     url: "/user/checkPassword",
            //     isArray: false
            // },
            getList: {
                cache: false,
                method: "POST",
                url: "/user/list",
                isArray: false
            },
            userEdit: {
                cache: false,
                method: "POST",
                url: "/user/edit",
                isArray: false
            },
            getUserInfo: {
                cache: false,
                method: "POST",
                url: "/user/info",
                isArray: false
            },
            getConfig: {
                cache: false,
                method: "GET",
                url: "/index/getConfig",
                isArray: false
            }
        });
    }])
    .factory("topic", ["$resource", function ($resource) {
        return $resource("", {}, {
            getList: {
                cache: false,
                method: "POST",
                url: "/topic/list",
                isArray: false
            },
            getInfo: {
                cache: false,
                method: "POST",
                url: "/topic/info",
                isArray: false
            },
            saveInfo: {
                cache: false,
                method: "POST",
                url: "/topic/save",
                isArray: false
            },
            getComments: {
                cache: false,
                method: "POST",
                url: "/topic/comment",
                isArray: false
            },
            invalid: {
                cache: false,
                method: "POST",
                url: "/topic/invalid",
                isArray: false
            },
            effective: {
                cache: false,
                method: "POST",
                url: "/topic/effective",
                isArray: false
            },
            updateTop: {
                cache: false,
                method: "POST",
                url: "/topic/updateTop",
                isArray: false
            }
        });
    }])
    .factory("welfare", ["$resource", function ($resource) {
        return $resource("", {}, {
            getWelfareList: {
                cache: false,
                method: "POST",
                url: "/welfare/pageList",
                isArray: false
            },
            saveWelfare: {
                cache: false,
                method: "POST",
                url: "/welfare/save",
                isArray: false
            },
            pushWelfare: {
                cache: false,
                method: "POST",
                url: "/welfare/push",
                isArray: false
            },
            deleteWelfare: {
                cache: false,
                method: "POST",
                url: "/welfare/delete",
                isArray: false
            },
            getWelfareItemList: {
                cache: false,
                method: "POST",
                url: "/welfareItem/list",
                isArray: false
            },
            uploadWelfareItem: {
                cache: false,
                method: "POST",
                url: "/welfareItem/upload",
                isArray: false
            }
        });
    }])
    // .factory("activitySign", ["$resource", function ($resource) {
    //     return $resource("", {}, {
    //         listByUser: {
    //             cache: false,
    //             method: "POST",
    //             url: "/activitySign/listByUser",
    //             isArray: false
    //         }
    //     });
    // }])
    // .factory("groupVerify", ["$resource", function ($resource) {
    //     return $resource("", {}, {
    //         getList: {
    //             cache: false,
    //             method: "POST",
    //             url: "/orgVerify/list",
    //             isArray: false
    //         },
    //         checkFail: {
    //             cache: false,
    //             method: "POST",
    //             url: "/orgVerify/checkFail",
    //             isArray: false
    //         },
    //         checkSuccess: {
    //             cache: false,
    //             method: "POST",
    //             url: "/orgVerify/checkSuccess",
    //             isArray: false
    //         }
    //     });
    // }])
;
/**
 * Created by cjd on 2016/6/13.
 */
angular.module("app").controller("settingCtrl", ["$scope", "$http", "org", function ($scope, $http, org) {
    $scope.saveOrg = function () {
        if(confirm("是否确定执行该操作?")){
            delete $scope.orgInfo.createTime;
            org.saveOrg({}, $scope.orgInfo, function (data) {
                if (data.statusCode == 0) {
                    alert("操作成功!");
                }
            });
        }
    };
    $scope.orgInfo = $scope.userInfo.organization;
    $scope.provinceChange = function(){
        $scope.orgInfo.city = city.filter(function(item){
            return item.ProID == $scope.orgInfo.province;
        })[0].CityID;
    };
    $scope.cityChange = function(){
        $scope.orgInfo.county = District.filter(function(item){
            return item.CityID == $scope.orgInfo.city;
        })[0].Id;
    }
}]);
angular.module("app").controller("welcomeCtrl", ["$scope", "$http", "$timeout","org", function($scope, $http, $timeout,org) {
    $scope.orgCountVo = {};
    $scope.getMonthList = function (number) {
        var monList = [];
        var d = new Date();
        var currYear = d.getFullYear();
        var currMon = d.getMonth();  // 获取上一个月份数值，此处不需要+1
        for(var i = 0; i < number; i++){
            if(currMon < 10){
                monList.push("" + currYear + "-0" + currMon);
            }else{
                monList.push("" + currYear + "-" + currMon);
            }
            currMon -= 1; // 获取上一个月份
            if(currMon == 0){
                currYear -= 1;
                currMon = 12;
            }
        }
        return monList.sort();
    };

    // org.count({}, {test:1}, function (data) {
    //     if (data.statusCode == 0) {
    //         $scope.orgCountVo = data.data.orgCountVo;
    //         $scope.activityList = data.data.activityStr.split(",");
    //         $scope.timeList = data.data.timeStr.split(",");
    //         $scope.volunteerList = data.data.volunteerStr.split(",");
    //         var dataSource = [];
    //         $scope.getMonthList(12).forEach(function (item,index) {
    //             var obj = {};
    //             obj.Month = item;
    //             obj.volunteer = +$scope.volunteerList[index];
    //             obj.time = +$scope.timeList[index];
    //             obj.activity = +$scope.activityList[index];
    //             dataSource.push(obj);
    //         });
    //         $scope.volunteerChartConfig.dataSource = $scope.activityChartConfig.dataSource = $scope.timeChartConfig.dataSource = dataSource;
    //     } else {
    //         alert(data.statusMessage)
    //     }
    // });

    $scope.volunteerChartConfig = {
        bindingOptions: {
            dataSource: "volunteerChartConfig.dataSource"
        },
        dataSource:[],
        commonSeriesSettings: {
            argumentField: "Month",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        series: [
            { valueField: "volunteer", name: "志愿者(人)" }
        ],
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center",
            itemTextPosition: "bottom"
        },
        title: {
            text: "志愿者增量图"
            // subtitle: {
            //     text: "(Millions of Tons, Oil Equivalent)"
            // }
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: arg.valueText + "人"
                };
            }
        }
    };

    $scope.activityChartConfig = {
        bindingOptions: {
            dataSource: "activityChartConfig.dataSource"
        },
        dataSource:[],
        commonSeriesSettings: {
            argumentField: "Month",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        series: [
            { valueField: "activity", name: "活动(次)" }
        ],
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center",
            itemTextPosition: "bottom"
        },
        title: {
            text: "活动增量图"
            // subtitle: {
            //     text: "(Millions of Tons, Oil Equivalent)"
            // }
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: arg.valueText + "次"
                };
            }
        }
    };

    $scope.timeChartConfig = {
        bindingOptions: {
            dataSource: "timeChartConfig.dataSource"
        },
        dataSource:[],
        commonSeriesSettings: {
            argumentField: "Month",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        series: [
            { valueField: "time", name: "公益时间(分钟)" }
        ],
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center",
            itemTextPosition: "bottom"
        },
        title: {
            text: "公益时间增量图"
            // subtitle: {
            //     text: "(Millions of Tons, Oil Equivalent)"
            // }
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: arg.valueText + "分钟"
                };
            }
        }
    };
}]);

/**
 * Created by cjd on 2016/6/12.
 */
angular.module("app").controller("group.activityList.Ctrl", ["$scope", "activitySign","$stateParams", function ($scope,activitySign,$stateParams) {
    $scope.activityGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "activityGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "realName",
            alignment: "center",
            width:200,
            caption: "昵称"
        }, {
            dataField: "nickName",
            alignment: "center",
            width:200,
            caption: "真名"
        }, {
            dataField: "name",
            alignment: "center",
            caption: "活动名称"
        }, {
            dataField: "times",
            alignment: "center",
            width:200,
            caption: "公益时间"
        }]
    };
    $scope.getList = function (userId) {
        activitySign.listByUser({}, {userId: userId}, function (data) {
            if (data.statusCode == 0) {
                $scope.activityGridConfig.dataSource = data.data;
            }
        });
    };
    $scope.getList($stateParams.userId);
}]);
/**
 * Created by cjd on 2016/5/10.
 */
angular.module("app").controller("group.list.Ctrl", ["$scope", "group", "$timeout", function ($scope, group, $timeout) {
    $scope.groupGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "groupGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "name",
            alignment: "center",
            caption: "社团名称"
        }, {
            dataField: "times",
            alignment: "center",
            caption: "公益时间"
        }, {
            dataField: "volunteers",
            alignment: "center",
            width:80,
            caption: "成员数量"
        }, {
            dataField: "actvitys",
            alignment: "center",
            width:80,
            caption: "活动数量"
        }, {
            dataField: "monitor",
            alignment: "center",
            caption: "负责人"
        }, {
            dataField: "phone",
            alignment: "center",
            caption: "联系电话"
        }, {
            dataField: "delStatus",
            alignment: "center",
            width:60,
            cellTemplate: "statusCellTemplate",
            caption: "状态"
        }, {
            dataField: "operation",
            alignment: "center",
            cellTemplate: "operationCellTemplate",
            caption: "操作"
        }]
    };
    $scope.orgParent = $scope.$parent.treeViewDataSource[0].orgId;
    $scope.getList = function (orgId) {
        group.listByOrg({}, {orgId: orgId}, function (data) {
            if (data.statusCode == 0) {
                $scope.groupGridConfig.dataSource = data.data;
            }
        });
    };
    $scope.treeViewConfig = angular.copy($scope.$parent.treeViewConfig);
    $scope.treeViewConfig.onItemClick = function (e) {
        $scope.getList(e.itemData.orgId);
        $scope.orgParent = e.itemData.orgId;
        $scope.groupInfo = {};
    };

    $scope.showGroupInfo = function (groupInfo) {
        $scope.groupInfo = groupInfo;
    };
    $scope.showVolunteerList = function (groupInfo) {
        location.href = "#/home/group/volunteerList/" + groupInfo.id;
    };
    $scope.getList($scope.$parent.treeViewDataSource[0].orgId);
}]);
/**
 * Created by cjd on 2016/6/16.
 */
angular.module("app").controller("group.info.Ctrl", ["$scope", "group","$stateParams", function ($scope, group,$stateParams) {
    $scope.getGroupInfo = function(groupId){
        group.getGroupInfo({}, {id: groupId}, function (data) {
            if (data.statusCode == 0) {
                $scope.groupInfo = data.data;
            }
        });
    };
    if($stateParams.groupId){
        $scope.getGroupInfo($stateParams.groupId);
    }
}]);
/**
 * Created by cjd on 2016/6/14.
 */
angular.module("app").controller("group.verify.Ctrl", ["$scope", "groupVerify","$stateParams", function ($scope, groupVerify,$stateParams) {
    $scope.statusEnum = {"0":"待审核","-1":"已拒绝","2":"已通过"};
    $scope.columns = [
        {
        dataField: "groupName",
        alignment: "center",
        caption: "申请社团"
    }, 
        {
        dataField: "createTime",
        alignment: "center",
        cellTemplate: "createTimeCellTemplate",
        caption: "申请日期"
    },  
        {
        dataField: "status",
        alignment: "center",
        cellTemplate: "statusCellTemplate",
        width: 60,
        caption: "状态"
    }, 
        null, 
        {
        dataField: "operation",
        alignment: "center",
        cellTemplate: "operationCellTemplate",
        caption: "操作"
    }
    ];
    $scope.orgVerifyListGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "orgVerifyListGridConfig.dataSource",
            columns: "columns"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据"
    };
    $scope.orgVerifyHistoryGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "orgVerifyHistoryGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        // searchPanel: {
        //     visible: true,
        //     width: 200,
        //     placeholder: "输入关键字进行查询"
        // },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "createTime",
            alignment: "center",
            cellTemplate: "createTimeCellTemplate",
            caption: "申请日期"
        }, {
            dataField: "operation",
            alignment: "center",
            cellTemplate: "operationCellTemplate",
            caption: "审核"
        }]
    };
    $scope.changeStatus = function(status){
        if($scope.dataSource && $scope.dataSource.length){
            $scope.orgVerifyListGridConfig.dataSource = $scope.dataSource.filter(function(item){
                return item.status == status;
            });
            if(status == 0 && $scope.columns[3]){
                delete $scope.columns[3]
            }
            else if(status != 0 && !$scope.columns[3]){
                $scope.columns[3] = {
                    dataField: "verifyTime",
                    alignment: "center",
                    cellTemplate: "verifyTimeCellTemplate",
                    caption: "审核日期"
                }
            }
            $scope.orgVerifyListCount = $scope.orgVerifyListGridConfig.dataSource.length;
            for (var i in $scope.$parent.verifyTabs) {
                $scope.$parent.verifyTabs[i] = false;
            }
            $scope.$parent.verifyTabs[status] = true;
        }
    };
    $scope.showGroupInfo = function (applyInfo) {
        location.href = "#/home/group/info/" + applyInfo.groupId;
    };
    $scope.Verify = function(applyInfo){
        if(applyInfo.status == 0){
            $scope.applyInfo = angular.copy(applyInfo);
        }
        $scope.showVerifyHistory(applyInfo);
    };
    $scope.showVerifyHistory = function(applyInfo){
        $scope.type = "view";
        $scope.orgVerifyHistoryGridConfig.dataSource = $scope.dataSource.filter(function(item){
            return item.groupId == applyInfo.groupId;
        });
        $scope.orgVerifyHistoryGridConfig.dataSource.sort(function(a,b){return b.verifyTime - a.verifyTime});
    };
    $scope.getList = function(){
        groupVerify.getList({}, {test: 1}, function (data) {
            if (data.statusCode == 0) {
                $scope.dataSource = data.data;
                $scope.orgVerifyListGridConfig.dataSource = $scope.dataSource.filter(function(item){
                    return item.status == 0;
                });
                $scope.orgVerifyListCount = $scope.orgVerifyListGridConfig.dataSource.length;
            }
        });
    };
    $scope.check = function(){
        if(confirm("是否确定执行该操作?")){
            if($scope.applyInfo.status == -1){
                $scope.checkFail($scope.applyInfo);
            }
            else if($scope.applyInfo.status == 2){
                $scope.checkSuccess($scope.applyInfo);
            }
        }
    };
    $scope.checkSuccess = function(applyInfo){
        groupVerify.checkSuccess({}, {id: applyInfo.id,remark:applyInfo.remark}, function (data) {
            if (data.statusCode == 0) {
                alert("操作成功!");
                $scope.getList();
                $scope.applyInfo = {};
                $scope.type = "list";
            }
            else{
                alert(data.statusMessage)
            }
        });
    };
    $scope.checkFail = function(applyInfo){
        groupVerify.checkFail({}, {id: applyInfo.id,remark:applyInfo.remark}, function (data) {
            if (data.statusCode == 0) {
                alert("操作成功!");
                $scope.getList();
                $scope.applyInfo = {};
                $scope.type = "list";
            }
            else{
                alert(data.statusMessage)
            }
        });
    };
    $scope.getList();
}]);
/**
 * Created by cjd on 2016/6/12.
 */
angular.module("app").controller("group.volunteerList.Ctrl", ["$scope", "group","$stateParams", function ($scope, group,$stateParams) {
    $scope.volunteerGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "volunteerGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "realName",
            alignment: "center",
            caption: "姓名"
        }, {
            dataField: "mobile",
            alignment: "center",
            caption: "手机号"
        }, {
            dataField: "acts",
            alignment: "center",
            width:80,
            caption: "活动次数"
        }, {
            dataField: "times",
            alignment: "center",
            width:80,
            caption: "公益时间"
        }, {
            dataField: "operation",
            alignment: "center",
            cellTemplate: "operationCellTemplate",
            caption: "操作"
        }]
    };
    $scope.getList = function (groupId) {
        group.volListById({}, {id: groupId}, function (data) {
            if (data.statusCode == 0) {
                $scope.volunteerGridConfig.dataSource = data.data;
            }
        });
    };

    $scope.showActivityList = function (volunteerInfo) {
        location.href = "#/home/group/activityList/" + volunteerInfo.id;
    };
    $scope.getList($stateParams.groupId);
}]);
/**
 * Created by cjd on 2016/6/28.
 */
angular.module("app").controller("topic.comments.Ctrl", ["$scope", "$http", "$stateParams", "topic", function ($scope, $http, $stateParams, topic) {
    if ($stateParams.id) {
        topic.getComments({}, {id: $stateParams.id}, function (data) {
            if (data.statusCode == 0) {
                $scope.commentList = data.data;
            } else {
                alert(data.statusMessage)
            }
        })
    }
}]);
/**
 * Created by cjd on 2016/6/24.
 */
angular.module("app").controller("topic.info.Ctrl", ["$scope", "$http", "$stateParams", "topic","$timeout", function ($scope, $http, $stateParams, topic,$timeout) {
    if ($stateParams.id) {
        topic.getInfo({}, {id: $stateParams.id}, function (data) {
            if (data.statusCode == 0) {
                $scope.topicInfo = data.data;
                try{
                    $scope.topicInfo.intro = JSON.parse($scope.topicInfo.intro);
                }
                catch (e){
                    $scope.topicInfo.intro = [];
                }
            } else {
                alert(data.statusMessage)
            }
        })
    }
    else {
        $scope.topicInfo = {top: 1};
    }
    $scope.addIntroItem = function () {
        if (!$scope.topicInfo.intro) {
            $scope.topicInfo.intro = [];
        }
        var item = {type: "text", sort: $scope.topicInfo.intro.length || 0};
        $scope.topicInfo.intro.push(item);
    };
    $scope.removeIntroItem = function (currItem) {
        if (confirm("确定执行该操作吗?")) {
            $scope.topicInfo.intro.forEach(function (item, index) {
                if (currItem.sort == item.sort) {
                    $scope.topicInfo.intro.splice(index, 1)
                }
            })
        }
    };
    $scope.saveTopicInfo = function () {
        var tmp = angular.copy($scope.topicInfo);
        tmp.intro = JSON.stringify(tmp.intro);
        topic.saveInfo({}, tmp, function (data) {
            if (data.statusCode == 0) {
                alert("保存成功");
                $scope.goBack();
            } else {
                alert(data.statusMessage)
            }
        })
    }
    $scope.uploadPhoto = function(file,item){
        var form = new FormData();
        form.append("file", file);
        form.append("key", new Date().getTime() + /\.[^\.]+$/.exec(file.name)[0]);
        form.append("token", $scope.$parent.qiniuToken);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://upload.qiniu.com/", true);
        function callback() {
            if (xhr.readyState == 4) {
                $timeout(function() {
                    var data = angular.fromJson(xhr.responseText);
                    if (data.key) {
                        item.background = "http://img.dakaqi.cn/" + data.key;
                    } else if (data.code) {
                        alert(data.error);
                        return;
                    }
                }, 3000);
            }
        }
        xhr.onreadystatechange = callback;
        xhr.send(form);
    }
}]);
/**
 * Created by cjd on 2016/6/24.
 */
angular.module("app").controller("topic.list.Ctrl", ["$scope", "topic", function ($scope, topic) {
    $scope.search = {display: 1, key: ""};
    $scope.searchTopicList = function () {
        topic.getList({}, {display: $scope.search.display, key: $scope.search.key}, function (data) {
            if (data.statusCode == 0) {
                $scope.topicList = data.data;
            } else {
                alert(data.statusMessage)
            }
        })
    };
    $scope.topicDisplay = function(item){
        if(confirm("确定执行该操作吗?")){
            if(item.display){
                /*置为无效*/
                topic.invalid({}, {id: item.id}, function (data) {
                    if (data.statusCode == 0) {
                        alert("操作成功!");
                        $scope.searchTopicList();
                    } else {
                        alert(data.statusMessage)
                    }
                })
            }
            else{
                topic.effective({}, {id: item.id}, function (data) {
                    if (data.statusCode == 0) {
                        alert("操作成功!");
                        $scope.searchTopicList();
                    } else {
                        alert(data.statusMessage)
                    }
                })
            }
        }
    };
    $scope.updateTop = function (item) {
        if(confirm("确定执行该操作吗?")){
            topic.updateTop({}, {id: item.id}, function (data) {
                if (data.statusCode == 0) {
                    alert("操作成功!");
                    $scope.searchTopicList();
                } else {
                    alert(data.statusMessage)
                }
            })
        }
    };
    $scope.topicEdit = function (item) {
        location.href = "#/home/topic/info/" + item.id;
    };
    $scope.topicCreate = function () {
        location.href = "#/home/topic/info/";
    };
    $scope.searchTopicList();
}]);
/**
 * Created by cjd on 2016/6/9.
 */
angular.module("app").controller("user.changePassword.Ctrl", ["$scope", "$http", "User", function ($scope, $http, User) {
    $scope.editPassword = function(){
        if($scope.newPW != $scope.newPW2){
            alert("两次输入的密码不一致,请重新输入!");
            return;
        }
        User.changePassword({}, {manageId:$scope.$parent.userInfo.manageId,oldPassword:$scope.password,NewPassword: $scope.newPW2}, function (data) {
            if (data.statusCode == 0) {
                alert("修改密码成功,请重新登录!");
                sessionStorage.clear();
                location.href = "#/login";
            } else {
                alert("原始密码错误,请重新输入!")
            }
        })
    };
}]);
angular.module("app").controller("user.manageList.Ctrl", ["$scope", "$state", "User", function ($scope, $state, User) {
    $scope.search = { roleId: "", key: "" };
    $scope.canEdit = $scope.userInfo.roles.indexOf("{1}") >= 0;
    $scope.userGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "userGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "manageName",
            alignment: "center",
            caption: "用户名"
        }, {
                dataField: "phone",
                alignment: "center",
                caption: "手机号"
            }, {
                dataField: "nickName",
                alignment: "center",
                caption: "昵称"
            }, {
                dataField: "roles",
                alignment: "center",
                customizeText: function (cellInfo) {
                    var str = "";
                    cellInfo.value.split(",").forEach(function (item) {
                        var tmp = $scope.$parent.roleDict[item.replace(/[^\d]+/g, "")];
                        if (tmp) {
                            str += tmp.text + ";"
                        }
                    });
                    return str;
                },
                caption: "权限"
            }, {
                dataField: "status",
                alignment: "center",
                cellTemplate: "statusCellTemplate",
                width: 60,
                caption: "状态"
            }, {
                dataField: "operation",
                alignment: "center",
                cellTemplate: "operationCellTemplate",
                caption: "操作"
            }]
    };
    $scope.getUserList = function () {
        User.getList({}, $scope.search, function (data) {
            if (data.statusCode == 0) {
                $scope.userGridConfig.dataSource = data.data;
            }
            else if (data.statusCode == -4) {
                alert("用户没有权限");
            } else {
                alert(data.statusMessage)
            }
        })
    };
    $scope.showManagerInfo = function (manage) {
        $state.go("home.user.manageInfo", { manageInfo: manage, manageId: manage.manageId, type: "view" })
    }
    $scope.createManagerInfo = function () {
        $state.go("home.user.manageInfo", { type: "create" })
    };
    $scope.editManagerInfo = function (manage) {
        $state.go("home.user.manageInfo", { manageInfo: manage, manageId: manage.manageId, type: "edit" })
    };
    $scope.getUserList();
}]);
angular.module("app").controller("user.manageInfo.Ctrl", ["$scope", "$stateParams", "User", function ($scope, $stateParams, User) {
    $scope.roleDict = angular.copy($scope.$parent.roleDict);
    if ($stateParams.manageInfo) {
        $scope.manageInfo = $stateParams.manageInfo;
        $scope.manageInfo.roles.split(",").forEach(function (item) {
            var tmp = $scope.roleDict[item.replace(/[^\d]+/g, "")];
            if (tmp) {
                tmp.checked = true;
            }
        });
    }
    else if ($stateParams.manageId) {
        User.getUserInfo({}, { userId: $stateParams.manageId }, function (data) {
            if (data.statusCode == 0) {
                $scope.manageInfo = data.data;
                $scope.manageInfo.roles.split(",").forEach(function (item) {
                    var tmp = $scope.roleDict[item.replace(/[^\d]+/g, "")];
                    if (tmp) {
                        tmp.checked = true;
                    }
                });
            } else {
                alert(data.statusMessage)
            }
        })
    }
    else {
        $scope.manageInfo = {};
    }

    $scope.type = $stateParams.type;
    $scope.types = { create: "创建", edit: "编辑", view: "查看" }
    $scope.roles = {};
    $scope.addRole = function (roleId, item, event) {
        if (event.currentTarget.checked) {
            $scope.roles[roleId] = "{" + roleId + "}";
            item.checked = true;
        }
        else {
            delete $scope.roles[roleId];
            item.checked = false;
        }
    };
    $scope.saveManageInfo = function () {
        var manageInfo = $scope.manageInfo;
        if ($scope.type == "create" && manageInfo.secondPassword != manageInfo.password) {
            alert("两次密码不一致,请重新输入!");
            return;
        }
        manageInfo.roles = "";
        for (var key in $scope.roleDict) {
            if ($scope.roleDict[key].checked) {
                manageInfo.roles += "{" + key + "}" + ",";
            }
        }
        delete manageInfo.secondPassword;
        if ($scope.type == "edit") {
            delete manageInfo.password;
        }
        User.userEdit({}, manageInfo, function (data) {
            if (data.statusCode == 0) {
                alert("更新成功!");
                $scope.goBack();
            } else {
                alert(data.statusMessage)
            }
        })
    };
}]);
/**
 * Created by cjd on 2016/6/9.
 */
angular.module("app").controller("org.info.Ctrl", ["$scope", "$http", "org", function ($scope, $http, org) {
    $scope.treeViewConfig = angular.copy($scope.$parent.treeViewConfig);
    $scope.treeViewConfig.onItemClick = function(e){
        $scope.orgInfo = e.itemData;
    };
    $scope.orgInfo = $scope.$parent.treeViewDataSource[0];
}]);
/**
 * Created by cjd on 2016/6/7.
 */
angular.module("app").controller("org.list.Ctrl", ["$scope", "$http", "org", function ($scope, $http, org) {
    $scope.orgGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "orgGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "orgName",
            alignment: "center",
            caption: "组织名称"
        }, {
            dataField: "onePass",
            alignment: "center",
            caption: "一号通"
        }, {
            dataField: "orgCode",
            alignment: "center",
            width: 80,
            caption: "组织编码"
        }, {
            dataField: "principal",
            alignment: "center",
            caption: "联系人"
        }, {
            dataField: "phone",
            alignment: "center",
            caption: "联系电话"
        }, {
            dataField: "status",
            alignment: "center",
            cellTemplate: "statusCellTemplate",
            width: 60,
            caption: "状态"
        }, {
            dataField: "operation",
            alignment: "center",
            cellTemplate: "operationCellTemplate",
            caption: "操作"
        }]
    };
    $scope.orgParent = $scope.$parent.treeViewDataSource[0].orgId;
    $scope.getList = function (orgId) {
        org.getList({}, {orgId: orgId}, function (data) {
            if (data.statusCode == 0) {
                $scope.orgGridConfig.dataSource = data.data.filter(function(item){
                    return item.orgId != item.orgParent
                });
            }
        });
    };
    $scope.updateOrgStatus = function (orgInfo) {
        org.updateStatus({}, {orgId: orgInfo.orgId}, function (data) {
            if (data.statusCode == 0) {
                if (orgInfo.status == 10) {
                    orgInfo.status = 20;
                }
                else {
                    orgInfo.status = 10;
                }
                alert("更新成功!")
            }
            else {
                alert(data.statusMessage)
            }
        });
    };
    $scope.treeViewConfig = angular.copy($scope.$parent.treeViewConfig);
    $scope.treeViewConfig.onItemClick = function (e) {
        $scope.getList(e.itemData.orgId);
        $scope.orgParent = e.itemData.orgId;
        $scope.orgInfo = {};
    };
    $scope.showOrgInfo = function (orgInfo) {
        $scope.orgInfo = orgInfo;
        $scope.type = "view";
        $scope.provinceChange("view");
        $scope.cityChange("view");
    };
    $scope.editOrgInfo = function (orgInfo) {
        $scope.orgInfo = orgInfo;
        $scope.type = "edit";
        $scope.provinceChange("view");
        $scope.cityChange("view");
    };
    $scope.saveOrg = function () {
        if($scope.isSocialCreditCode($scope.orgInfo.orgCode)){
            if(confirm("是否确定执行该操作?")){
                delete $scope.orgInfo.createTime;
                org.saveOrg({}, $scope.orgInfo, function (data) {
                    if (data.statusCode == 0) {
                        alert("操作成功!");
                        location.reload(true)
                    }
                });
            }
        }
        else{
            alert("组织编码有误,请重新输入!")
        }
    };
    $scope.isSocialCreditCode = function (code) {
        if (code.length != 18) {
            return false;
        }//必须是18位
        //登记管理部门代码1位
        var first = code.substring(0, 1);
        if (!/^[1,5,9,Y]{1}$/.test(first)) {
            return false;
        }//第一位数必须是以1，5，9或Y开头

        //机构类别代码1位
        var second = code.substring(1, 2);
        switch (first) {
            case "1" :
                if (!/^[1,2,3,9]$/.test(second)) {
                    return false;
                };
                break;//机构编制
            case "5" :
                if (!/^[1,2,3,9]$/.test(second)) {
                    return false;
                };
                break;//民政
            case "9" :
                if (!/^[1,2,3]$/.test(second)) {
                    return false;
                };
                break;//工商
            case "Y" :
                if (!/^[1]$/.test(second)) {
                    return false;
                };
                break;//其他
        }

        //登记管理机关行政区划码6位
        var xz = code.substring(2, 8);
        if (!/^[0-9]{6}$/.test(xz)) {
            return false;
        }

        //主体标识码（组织机构代码）9位
        var jg = code.substring(8, 17);
        if (!/^[0-9,A-H,J-N,P-R,T-U,W-Y]{9}$/.test(jg)) {
            return false;
        }//阿拉伯数字或者大写英语字母（不含I,O,Z,S,V）

        //第18位校验码
        var et = code.substring(17);

        /**计算第18位校证码*/
        //17位Ci的值
        var dmj = "0123456789ABCDEFGHJKLMNPQRTUWXY";
        var dmjv = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30);//字符集对应的值
        var Ci = new Array(17);
        for (var i = 0; i < 17; i++) {//17位
            var val = code.charAt(i);
            var indx = dmj.indexOf(val);
            Ci[i] = dmjv[indx];
        }
        //加权因子Wi
        var Wi = new Array(1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28);
        //Ci*Wi
        var CWi = new Array(17);
        var total = new Number(0);
        for (var i = 0; i < 17; i++) {
            var val = Ci[i] * Wi[i];
            CWi[i] = val;
            total += val;
        }
        var index = total % 31;
        var jm = "";
        if (index == 0) {
            jm = "0";
        } else {
            jm = dmj.charAt(31 - total % 31);
        }
        if (jm != et) {
            return false;
        }
        return true;
    };
    $scope.updateStatus = function (orgInfo) {
        if(confirm("是否确定执行该操作?")){
            $scope.updateOrgStatus(orgInfo);
        }
    };
    $scope.getList($scope.$parent.treeViewDataSource[0].orgId);
    $scope.createOrg = function () {
        $scope.type = "edit";
        $scope.orgInfo = {orgParent:$scope.orgParent,province:$scope.$parent.treeViewDataSource[0].province};
        $scope.provinceChange();
        $scope.cityChange();
    };
    $scope.provinceChange = function(type){
        $scope.currCityList = city.filter(function (item) {
            return item.ProID == $scope.orgInfo.province;
        });
        if(type != "view"){
            $scope.orgInfo.city = $scope.currCityList[0].CityID;
            $scope.cityChange();
        }
    };
    $scope.cityChange = function(type){
        $scope.currDistrictList = District.filter(function (item) {
            return item.CityID == $scope.orgInfo.city;
        });
        if(type != "view"){
            $scope.orgInfo.county = $scope.currDistrictList[0].Id;
        }
    }
}]);
/**
 * Created by cjd on 2016/6/7.
 */
angular.module("app").controller("org.managerList.Ctrl", ["$scope", "$http", "User", function ($scope, $http, User) {
    $scope.managerGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "managerGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "userName",
            alignment: "center",
            caption: "用户名"
        }, {
            dataField: "phone",
            alignment: "center",
            caption: "手机号"
        }, {
            dataField: "certificateType",
            alignment: "center",
            width: 100,
            cellTemplate: "certificateTypeCellTemplate",
            caption: "证件类型"
        }, {
            dataField: "certificateCode",
            alignment: "center",
            caption: "证件号码"
        }, {
            dataField: "status",
            alignment: "center",
            cellTemplate: "statusCellTemplate",
            width: 60,
            caption: "状态"
        }, {
            dataField: "operation",
            alignment: "center",
            cellTemplate: "operationCellTemplate",
            caption: "操作"
        }]
    };
    $scope.orgParent = $scope.$parent.treeViewDataSource[0].orgId;
    $scope.getList = function (orgId) {
        User.getList({}, {orgId: orgId}, function (data) {
            if (data.statusCode == 0) {
                $scope.managerGridConfig.dataSource = data.data;
            }
        });
    };
    $scope.updateManagerStatus = function (managerInfo) {
        User.updateStatus({}, {userId: managerInfo.userId}, function (data) {
            if (data.statusCode == 0) {
                if (managerInfo.status == 10) {
                    managerInfo.status = 20;
                }
                else {
                    managerInfo.status = 10;
                }
                alert("更新成功!")
            }
            else {
                alert(data.statusMessage)
            }
        });
    };
    $scope.treeViewConfig = angular.copy($scope.$parent.treeViewConfig);
    $scope.treeViewConfig.onItemClick = function (e) {
        $scope.getList(e.itemData.orgId);
        $scope.orgParent = e.itemData.orgId;
        $scope.managerInfo = {};
    };
    $scope.showManagerInfo = function (managerInfo) {
        $scope.managerInfo = managerInfo;
        $scope.type = "view";
    };
    $scope.editManagerInfo = function (managerInfo) {
        $scope.managerInfo = managerInfo;
        $scope.type = "edit";
    };
    $scope.saveManager = function () {
        if($scope.managerInfo.certificateType == 1 && !/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/.test($scope.managerInfo.certificateCode)){
            alert("请输入正确的身份证号!");
            return;
        }
        // else if($scope.managerInfo.certificateType == 2 && !/^1[45][0-9]{7}|G[0-9]{8}|P[0-9]{7}|S[0-9]{7,8}|D[0-9]+$/.test($scope.managerInfo.certificateCode)){
        //     alert("请输入正确的护照号码!");
        //     var re1 = /^[a-zA-Z]{5,17}$/;
        //     var re2 = /^[a-zA-Z0-9]{5,17}$/;
        //     return;
        // }
        if(confirm("是否确定执行该操作?")){
            delete $scope.managerInfo.createTime;
            User.saveUser({}, $scope.managerInfo, function (data) {
                if (data.statusCode == 0) {
                    alert("操作成功!");
                    $scope.getList($scope.managerInfo.orgId);
                    $scope.managerInfo = {};
                }
                else{
                    alert(data.statusMessage)
                }
            });
        }
    };
    $scope.updateStatus = function (managerInfo) {
        if (confirm("是否确定执行该操作?")) {
            $scope.updateManagerStatus(managerInfo);
        }
    };
    $scope.getList($scope.$parent.treeViewDataSource[0].orgId);
    $scope.createManager = function () {
        $scope.type = "edit";
        $scope.managerInfo = {orgId:$scope.orgParent,status:10,certificateType:1,role:1};
    }
}]);
angular.module("app").controller("welfare.info.Ctrl", ["$scope", "$stateParams", "welfare","$timeout","$filter", function ($scope, $stateParams, welfare,$timeout,$filter) {
    $scope.provinceChange = function(){
        var provinceId = $scope.province.filter(function (item) {
            return item.ProName == $scope.welfareInfo.province;
        })[0].ProID;
        $scope.currCityList = city.filter(function (item) {
            return item.ProID == provinceId;
        });
    };
    if ($stateParams.welfareInfo) {
        $scope.welfareInfo = $stateParams.welfareInfo;
        $scope.welfareInfo.startDay = new Date($scope.welfareInfo.startDay);
        $scope.welfareInfo.endDay = new Date($scope.welfareInfo.endDay);
        $scope.welfareInfo.useStart = new Date($scope.welfareInfo.useStart);
        $scope.welfareInfo.useEnd = new Date($scope.welfareInfo.useEnd);
        try {
            $scope.welfareInfo.useDemo = JSON.parse($scope.welfareInfo.useDemo);
        }
        catch (e) {
            $scope.welfareInfo.useDemo = [];
        }
        if($scope.welfareInfo.area != "全国"){
            var tmp = $scope.welfareInfo.area.split(";");
            $scope.welfareInfo.province = tmp[0];
            $scope.welfareInfo.city = tmp[1];
            $scope.provinceChange();
            welfareInfo.area = "定向";
        }
    }
    else if ($stateParams.id) {
        // welfare.getUserInfo({}, { id: $stateParams.id }, function (data) {
        //     if (data.statusCode == 0) {
        //         $scope.manageInfo = data.data;
        //         $scope.manageInfo.roles.split(",").forEach(function (item) {
        //             var tmp = $scope.roleDict[item.replace(/[^\d]+/g, "")];
        //             if (tmp) {
        //                 tmp.checked = true;
        //             }
        //         });
        //     } else {
        //         alert(data.statusMessage)
        //     }
        // })
    }
    else {
        $scope.welfareInfo = { area: "全国", delStatus: 0, status: 0, type: 1, code: "0" };
        // $scope.provinceChange();
    }

    $scope.type = $stateParams.type;
    $scope.types = { create: "创建", edit: "编辑", view: "查看" };
    $scope.startDayConfig = {
        formatString: "yyyy-MM-dd HH:mm:ss",
        format: "datetime",
        bindingOptions: {
            value: "welfareInfo.startDay"
        }
    };
    $scope.endDayConfig = {
        formatString: "yyyy-MM-dd HH:mm:ss",
        format: "datetime",
        bindingOptions: {
            value: "welfareInfo.endDay"
        }
    };
    $scope.useStartConfig = {
        formatString: "yyyy-MM-dd HH:mm:ss",
        format: "datetime",
        bindingOptions: {
            value: "welfareInfo.useStart"
        }
    };
    $scope.useEndConfig = {
        formatString: "yyyy-MM-dd HH:mm:ss",
        format: "datetime",
        bindingOptions: {
            value: "welfareInfo.useEnd"
        }
    };
    $scope.addItem = function () {
        if (!$scope.welfareInfo.useDemo) {
            $scope.welfareInfo.useDemo = [];
        }
        var item = { type: "text", sort: $scope.welfareInfo.useDemo.length || 0 };
        $scope.welfareInfo.useDemo.push(item);
    };
    $scope.removeItem = function (currItem) {
        if (confirm("确定执行该操作吗?")) {
            $scope.welfareInfo.useDemo.forEach(function (item, index) {
                if (currItem.sort == item.sort) {
                    $scope.welfareInfo.useDemo.splice(index, 1)
                }
            })
        }
    };
    $scope.saveWelfareInfo = function () {
        if(!$scope.welfareInfo.province.length){
            alert("请选择正确兑换区域!")
            return;
        }
        var welfareInfo = angular.copy($scope.welfareInfo);
        if(welfareInfo.area == "定向"){
            welfareInfo.area = welfareInfo.province + ";" +(welfareInfo.city || "")
        }
        welfareInfo.startDay = $filter("date")(welfareInfo.startDay,"yyyy-MM-dd HH:mm:ss");
        welfareInfo.endDay = $filter("date")(welfareInfo.endDay,"yyyy-MM-dd HH:mm:ss");
        welfareInfo.useStart = $filter("date")(welfareInfo.useStart,"yyyy-MM-dd HH:mm:ss");
        welfareInfo.useEnd = $filter("date")(welfareInfo.useEnd,"yyyy-MM-dd HH:mm:ss");
        delete welfareInfo.province;
        welfare.saveWelfare({}, welfareInfo, function (data) {
            if (data.statusCode == 0) {
                alert("更新成功!");
                $scope.goBack();
            } else {
                alert(data.statusMessage)
            }
        })
    };
    
    $scope.uploadPhoto = function(file,item){
        var form = new FormData();
        form.append("file", file);
        form.append("key", new Date().getTime() + /\.[^\.]+$/.exec(file.name)[0]);
        form.append("token", $scope.$parent.qiniuToken);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://upload.qiniu.com/", true);
        function callback() {
            if (xhr.readyState == 4) {
                $timeout(function() {
                    var data = angular.fromJson(xhr.responseText);
                    if (data.key) {
                        item.img = "http://img.dakaqi.cn/" + data.key;
                    } else if (data.code) {
                        alert(data.error);
                        return;
                    }
                }, 3000);
            }
        }
        xhr.onreadystatechange = callback;
        xhr.send(form);
    }
}]);
angular.module("app").controller("welfare.welfareItemList.Ctrl", ["$scope", "$state", "welfare", "$timeout", function ($scope, $state, welfare, $timeout) {
    $scope.search = { id: "", code: "" };
    $scope.welfareItemGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "welfareItemGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "code",
            alignment: "center",
            caption: "券号"
        }, {
                dataField: "isChanage",
                alignment: "center",
                customizeText: function (cellInfo) {
                    var str = "未兑换";
                    if (cellInfo.value != 0) {
                        str = "已兑换";
                    }
                    return str;
                },
                caption: "是否兑换"
            }, {
                dataField: "isUse",
                alignment: "center",
                customizeText: function (cellInfo) {
                    var str = "未使用";
                    if (cellInfo.value != 0) {
                        str = "已使用";
                    }
                    return str;
                },
                caption: "是否使用"
            }, {
                dataField: "useTime",
                alignment: "center",
                cellTemplate: "useTimeCellTemplate",
                caption: "使用时间"
            }, {
                dataField: "createTime",
                alignment: "center",
                cellTemplate: "createTimeCellTemplate",
                caption: "创建时间"
            }, {
                dataField: "memberCode",
                alignment: "center",
                caption: "兑换人"
            }]
    };
    $scope.getWelfareItemList = function () {
        welfare.getWelfareItemList({}, $scope.search, function (data) {
            if (data.statusCode == 0) {
                $scope.welfareItemGridConfig.dataSource = data.data;
            }
            else if (data.statusCode == -4) {
                alert("用户没有权限");
            } else {
                alert(data.statusMessage)
            }
        })
    };
    $scope.getWelfareItemList();
    $scope.uploadWelfareItem = function (file) {
        var form = new FormData();
        form.append("file", file);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://test.dakaqi.cn:3030/platform/welfareItem/upload", true);
        function callback() {
            if (xhr.readyState == 4) {
                $timeout(function () {
                    var data = angular.fromJson(xhr.responseText);
                    if (data.statusCode == 0) {
                        alert("上传成功!");
                        document.getElementById('docFile').outerHTML = obj.outerHTML;
                    } else {
                        alert(data.statusMessage);
                    }
                }, 3000);
            }
        }
        xhr.onreadystatechange = callback;
        xhr.send(form);
    }
}]);
angular.module("app").controller("welfare.list.Ctrl", ["$scope", "welfare", "$state", function ($scope, welfare, $state) {
    $scope.search = { status: 1, name: "", pageIndex: 0, pageSize: 9999 };
    $scope.welfareType = { 1: "电影票", 2: "充值卡", 3: "优惠券" };
    $scope.searchWelfareList = function () {
        welfare.getWelfareList({}, $scope.search, function (data) {
            if (data.statusCode == 0) {
                $scope.welfareList = data.data.data;
            } else {
                alert(data.statusMessage)
            }
        })
    };
    $scope.welfareEdit = function (item) {
        $state.go("home.welfare.info", { welfareInfo: item, id: item.id, type: "edit" })
    };
    $scope.welfareCreate = function () {
        $state.go("home.welfare.info", { type: "create" })
    };
    $scope.welfareDel = function (item) {
        if (confirm("确定执行该操作吗?")) {
            welfare.deleteWelfare({}, { id: item.id }, function (data) {
                if (data.statusCode == 0) {
                    alert("操作成功!");
                    $scope.searchWelfareList();
                } else {
                    alert(data.statusMessage)
                }
            })
        }
    };
    $scope.welfarePush = function (item) {
        if (confirm("确定执行该操作吗?")) {
            welfare.pushWelfare({}, { id: item.id }, function (data) {
                if (data.statusCode == 0) {
                    alert("操作成功!");
                    $scope.searchWelfareList();
                } else {
                    alert("操作失败!")
                }
            })
        }
    }
    $scope.searchWelfareList();
}]);
angular.module("app").controller("homeCtrl", ["$scope", "$http", "$state", "$filter", "$timeout","qiniuToken", function ($scope, $http, $state, $filter, $timeout,qiniuToken) {
    if (sessionStorage.userInfo) {
        $scope.userInfo = JSON.parse(sessionStorage.userInfo);
    }
    else {
        location.href = "#/login";
    }
    $scope.qiniuToken = qiniuToken.data.qiniuToken;
    $scope.roleDict= {
        1:{text:"系统管理"},
        2:{text:"APP管理"},
        3:{text:"素材管理"},
        4:{text:"社团管理"},
        100001:{text:"重置密码"},
    };
    $scope.selectedItems = [];
    $scope.accordionDataSource = [
        {
            id: 1,
            title: "APP管理",
            menus: [{name: "话题列表", value: "home.topic.list"}
            ]
        },
        {
            id: 2,
            title: "权限管理",
            menus: [{name: "用户列表",value: "home.user.manageList"}]
            // menus: [{name: "角色列表", value: "home.role.list"},{name: "用户列表",value: "home.user.manageList"}]
        },
        {
            id: 3,
            title: "福利管理",
            menus: [{name: "福利列表", value: "home.welfare.list"},{name: "福利券列表",value: "home.welfare.welfareItemList"}]
        },
        {
            id: 4,
            title: "个人设置",
            menus: [{name: "修改密码", value: "home.user.changePassword"},{name: "退出",value: ""}]
        }
    ];
    // if($scope.userInfo.role == 2){
    //     $scope.accordionDataSource.push({
    //         id:3,
    //         title:"系统设置",
    //         menus:[{name:"机构信息设置",value:"home.setting"}]
    //     })
    // }
    $scope.accordionOptions = {
        dataSource: $scope.accordionDataSource,
        animationDuration: 300,
        collapsible: true,
        bindingOptions: {
            selectedItems: "selectedItems"
        }
    };

    $scope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) {
        if (toState.name.indexOf("topic") >= 0) {
            $scope.selectedItems = [$scope.accordionDataSource[0]];
        }
        else if (toState.name.indexOf("home.role.list") >= 0 || toState.name.indexOf("home.user.manageList") >= 0 || toState.name.indexOf("home.user.manageInfo") >= 0) {
            $scope.selectedItems = [$scope.accordionDataSource[1]];
        }
        else if (toState.name.indexOf("home.welfare.list") >= 0 || toState.name.indexOf("home.welfare.welfareItemList") >= 0) {
            $scope.selectedItems = [$scope.accordionDataSource[2]];
        }
        else if(toState.name.indexOf("home.user.changePassword") >= 0){
            $scope.selectedItems = [$scope.accordionDataSource[3]];
        }
    });

    $scope.logout = function () {
        if (confirm("确定要退出吗?")) {
            sessionStorage.clear();
            location.href = "#/login";
        }
    };
    $scope.eventStop = function ($event) {
        $event.stopPropagation();
    };
    $scope.goBack = function () {
        history.back();
    };
    // $scope.transformTreeData = function (data) {
    //     var arr = [];
    //     var obj = {};
    //     data.forEach(function (item) {
    //         item.href = item.orgId;
    //         item.id = item.orgId;
    //         item.text = item.orgName;
    //         item.expanded = true;
    //         obj[item.orgId] = item;
    //         if (item.orgId == $scope.userInfo.orgId) {
    //             arr.push(item);
    //         }
    //         else if (item.orgParent) {
    //             if (!obj[item.orgParent].items) {
    //                 obj[item.orgParent].items = [];
    //             }
    //             item.expanded = false;
    //             obj[item.orgParent].items.push(item);
    //         }
    //     });
    //     return arr;
    // };
    $scope.city = city;
    $scope.District = District;
    $scope.province = province;
    //
    // //District.forEach(function(item){
    // //    $scope.District[item.Id] = item;
    // //});
    // //city.forEach(function(item){
    // //    $scope.city[item.CityID] = item;
    // //});
    // //province.forEach(function(item){
    // //    $scope.province[item.ProID] = item;
    // //});
    //
    // $scope.treeViewConfig = {
    //     bindingOptions: {
    //         dataSource: "treeViewConfig.dataSource"
    //     },
    //     expandAllEnabled: true
    // };
    // $scope.treeViewDataSource = $scope.transformTreeData(treeViewDataSource.data);
    // $scope.treeViewDataSource[0].selected = true;
    // $scope.treeViewConfig.dataSource = $scope.treeViewDataSource;
    // $scope.orgList = {};
    // orgList.data.forEach(function (item) {
    //     $scope.orgList[item.orgId] = item;
    // });
    //
    // $scope.verifyTabs = {"0":true,"2":false,"-1":false};

    $scope.uploadPhoto = function(file,item){
        var form = new FormData();
        form.append("file", file);
        var xhr = new XMLHttpRequest();
        var apiBase = "";
        if(location.host.indexOf("localhost") >= 0){
            apiBase = "http://test.dakaqi.cn:3030/platform";
        }
        xhr.open("POST", apiBase + "/index/uploadFile", true);

        function callback() {
            if (xhr.readyState == 4) {
                $timeout(function() {
                    var data = angular.fromJson(xhr.responseText);
                    if (data.statusCode == -100) {
                        alert(data.statusMessage);
                        location.href = "#/login";
                    } else if (data.statusCode == -1) {
                        alert(data.statusMessage);
                        return;
                    }
                    $scope.$apply(function() {
                        item.img = data.statusMessage;
                    });
                }, 3000);
            }
        }
        xhr.onreadystatechange = callback;
        xhr.send(form);
    }
}]);
/**
 * Created by cjd on 2016/5/4.
 */
angular.module("app").controller("loginCtrl", ["$scope", "$http", '$timeout', "$state", "User", function ($scope, $http, $timeout, $state, User) {
    if(sessionStorage.userInfo){
        $state.go("home.welcome");//转跳到欢迎页
    }
    else{
        $scope.phone = "";// 账号
        $scope.password = "";//密码
        if (localStorage.remenberName) {//如果之前有记录账号，则显示账号
            $scope.remenberName = true;
            $scope.phone = localStorage.remenberName;
        }
        $scope.login = function () {//登录函数
            sessionStorage.clear();
            User.Login({}, {phone: $scope.phone, password: $scope.password}, function (data) {
                /*登录成功，并记录账号时，将账号记录到 localStorage
                 *如果取消勾选，清空localStorage
                 */
                if (data.statusCode == 0) {
                    sessionStorage.userInfo = JSON.stringify(data.data);
                    // $state.go("home.welcome");//转跳到欢迎页
                    $state.go("home.topic.list");
                } else {
                    alert("用户名密码错误!")
                }
            })
        }
    }
}]);
/**
 * Created by cjd on 2016/6/9.
 */
angular.module("app").controller("resetPassword.Ctrl", ["$scope", "$interval", "User", function ($scope, $interval, User) {
    $scope.resetPassword = function () {
        User.resetPassword({}, {
            password: $scope.password,
            code: $scope.checkCode,
            phone: $scope.phone
        }, function (data) {
            if (data.statusCode == 0) {
                alert("密码重置成功,请重新登录!");
                sessionStorage.clear();
                location.href = "#/login";
            } else {
                alert("重置密码出错,请重试!")
            }
        })
    };
    $scope.sendSMS = function () {
        if (!$scope.phone || $scope.phone.length == 0) {
            alert("手机号不能为空!");
            return;
        }
        if($scope.cd != "获取验证码"){
            return;
        }
        User.sendSMS({}, {phone: $scope.phone}, function (data) {
            if (data.statusCode == 0) {
                $scope.count = 60;
                $scope.timer = $interval(function () {
                    if ($scope.count == 0) {
                        $scope.cd = "获取验证码";
                        $interval.cancel($scope.timer);
                    }
                    else {
                        $scope.count--;
                        $scope.cd = "剩余" + $scope.count + "秒";
                    }
                }, 1000)
            }
            else if (data.statusCode == -2) {
                alert("该手机号不存在,请重新输入!")
            }
            else {
                alert(data.statusMessage)
            }
        })
    };
    $scope.cd = "获取验证码";
}]);